﻿using System;
using System.ComponentModel;
using System.Linq;

namespace Common.Helper
{
    public static class EnumExtensions
    {
        public static string ToDescription(this Enum en)
        {
            var type = en.GetType();

            var memInfo = type.GetMember(en.ToString());

            if (memInfo.Length > 0)
            {
                var attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

                if (attrs.Length > 0)
                    return ((DescriptionAttribute)attrs[0]).Description;
            }

            return en.ToString();
        }

        public static T ToEnumValue<T>(this string enumString) where T : struct
        {
            enumString = enumString.ToLower();

            var enumValues = Enum.GetValues(typeof(T)).Cast<Enum>().ToList();
            object enumValue = enumValues.Find(x => x.ToString().ToLower() == enumString || x.ToDescription().ToLower() == enumString);

            if (enumValue == null)
                throw new ArgumentException(String.Format("The value: '{0}' does not correspond to any valid enum values for enum: {1}", enumString, typeof(T).Name));

            return (T)enumValue;
        }

       
    }
}